<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Org\Image;
use DB;
// use Intervention\Image\ImageManagerStatic as Image;

class GoodController extends Controller
{
    public function index(Request $request)
    {
    	//保存搜索条件
        $where = [];
        //实例化要操作的表
        $db = DB::table('goods');
        //判断有没有搜索name字段的值
        if($request->has('sname')){
            // 获取要搜索的name字段的值
    	    $sname = $request->input('sname');
    	    //添加where模糊匹配条件
    	    $db->where('sname','like',"%{$sname}%");
    	    $where['sname'] = $sname;
        }
    	$list = $db->paginate(1);
    	return view('goods.index',['list'=>$list,'where'=>$where]);
    }
    //添加
    public function create()
    {
    	return view('goods.add');
    }

    public function store(Request $request)
    {
    	 // dd($request);
         if ($request->hasFile('pic')) {
            if ($request->file('pic')->isValid()) {
                $file = $request->file('pic');
                $ext = $file->getClientOriginalExtension();
                $picname = time().rand(1000,9999).'.'.$ext;
                $file->move('./uploads/',$picname);
                if($file->getError()>0){
                    echo '上传失败';
                }else{
                    // echo '上传成功';
                    if ($request->hasFile('bigpic')) {
                        if ($request->file('bigpic')->isValid()) {
                        $file = $request->file('bigpic');
                        $ext = $file->getClientOriginalExtension();
                        $picname = time().rand(1000,9999).'.'.$ext;
                        $file->move('./uploads/',$picname);
                        if($file->getError()>0){
                            echo '上传失败';
                        }else{
                            echo '上传成功';
                            
                        }
                    }
                }
            }
        }
    }

        // 1.使用自定义类进行图片缩放

        $img = new Image();
        $im = $img->open('./uploads/'.$picname);
        $im->thumb(100,100)->save('./uploads/s_'.$picname);
    	
        $data = $request->except('_token');
    	$m = DB::table('goods')->insertGetId($data);
    	if($m>0){
    		return redirect('admin/goods');
    	}
    }
    //删除
    public function destroy($id)
    {
    	$id = DB::table('goods')->where('id',$id)->delete();
    	if($id>0){
    		return redirect('admin/goods');
    	}
    }

    //修改
    public function edit($id)
    {
    	$goods = DB::table('goods')->where('id',$id)->first();
    	return view('goods.edit',['goods'=>$goods]);
    }

    public function update($id, Request $request)
    {
    	$data = $request->only('sname','type','price','pic','bigpic','stock','body','under','bin','Hlevel','discount');
    	$row = DB::table('goods')->where('id',$id)->update($data);
    	// dd($row);
    	if($row>0){
    		return redirect('admin/goods');
    	}
    }
    
}
